/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/flatten-binary-tree-to-linked-list
   @Language: C++
   @Datetime: 19-07-31 10:55
   */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

// Method 1, Recursion
class Solution {
public:
	void flatten(TreeNode* root) {
		if(root==NULL) return;
		TreeNode *right=root->right;
		root->right=root->left;
		flatten(root->left);
		root->left=NULL;
		for(; root->right; root=root->right);
		root->right=right;
		flatten(root->right);
	}
};

// Method 2, loop
class Solution {
public:
	void flatten(TreeNode* root) {
		for(TreeNode *left; root; root=root->right){
			if(root->left==NULL) continue;
			for(left=root->left; left->right; left=left->right);
			left->right=root->right;
			root->right=root->left;
			root->left=NULL;
		}
	}
};
